import React, { useState } from 'react';

interface Props {
  onClick?: Function;
  className?: string;
  children?: any;
}

export default function Touch(props: Props) {
  const [state, setState] = useState({
    startTime: 0,
    x: 0,
    y: 0,
    isMove: false,
  });
  const touchStart = (e: any) => {
    console.log('触摸开始Touch');
    state.startTime = Date.now();
    state.y = e.touches[0].clientY;
    state.x = e.touches[0].clientX;
    e.preventDefault();
    // console.log(e.touches[0].clientY);
  };

  // 移动
  const touchMove = (e: any) => {
    e.preventDefault();
    state.isMove = true;
    state.y = e.touches[0].clientY - state.y;
    state.x = e.touches[0].clientX - state.x;
  };

  const touchEnd = (e: any) => {
    console.log('触摸结束Touch');
    // console.log(state.y);
    // e.stopPropagation()
    if (!state.isMove) {
      state.y = 0;
      state.x = 0;
    }
    if (Date.now() - state.startTime < 300 && Math.abs(state.y) < 30 && Math.abs(state.x) < 30) {
      if (props.onClick) {
        props.onClick();
      }
    }
    setState({ ...state, isMove: false });
  };
  return (
    <div className={props.className} onTouchStart={touchStart} onTouchEnd={touchEnd} onTouchMove={touchMove}>
      {props.children}
    </div>
  );
}
